package com.zhang.controller;

import com.auth0.jwt.JWT;
import com.zhang.pojo.Result;
import com.zhang.pojo.User;
import com.zhang.service.UserService;
import com.zhang.utils.JwtUtil;
import com.zhang.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraintvalidation.SupportedValidationTarget;
import org.apache.ibatis.ognl.OgnlContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@Validated //开启注解校验
public class UserController {

    @Autowired
    private UserService userService;

    //注册
    @PostMapping("/register")    //^[^\s]{5,16}$:创建一个匹配5到16位非空字符的正则表达式
    public Result register(@Pattern(regexp = "^[^\\s]{5,16}$") String username, @Pattern(regexp = "^[^\\s]{5,16}$") String password) {
        //查询用户
        User user = userService.findByUserName(username);
        if (user == null) {
            //没有占用
            //注册
            userService.register(username, password);
            return Result.success();
        }else {
            //用户名被占用
            return Result.error("用户名被占用");
        }
    }

    //登录
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^[^\\s]{5,16}$") String username, @Pattern(regexp = "^[^\\s]{5,16}$") String password){
        //根据用户名查询用户
        User loginUser = userService.findByUserName(username);

        //判断用户是否存在
        if (loginUser==null){
            return Result.error("用户名错误");
        }

        //判断密码是否正确（注意数据库密码是密文）
        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())){
            //登录成功
            //将业务数据存进JWT载荷中
            //创建Map集合存放id和username数据
            Map<String, Object> claims= new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims); //返回token
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    //获取用户详细信息
    @GetMapping("/info")
    public Result<User> userInfo(@RequestHeader(name = "Authorization") String token){
        Map<String, Object> map = JwtUtil.parseToken(token); //获取token载荷
        String username = (String) map.get("username");//从载荷上获取username
        System.out.println("Map:"+username);
        username = "admin";//test
        User user = userService.findByUserNameWithRole(username);
        System.out.println("用户详细信息:"+user);
        return Result.success(user);
    }

}
